<template>
<a-card :bordered="false" class="db_console">
  <a-spin :spinning="spinning">
  <a-row :gutter="10">
      <a-col :md="6" >
        <a-card title="数据库连接信息" size="small" :bodyStyle="{'overflow-y': 'auto'}">
          <a slot="extra" href="#">
            <a-icon type="cloud-sync" title="刷新" @click="loadDataDb" class="mr-4 text-xl"  />
            <a-icon type="cloud-upload" title="创建新连接" @click="handleAdd" class="text-xl" />
          </a>
            <a-tree
              ref="dbTree"
              show-icon
              :tree-data="treeData"
              :load-data="onLoadData"
              :replaceFields="replaceFields"
              :loadedKeys="loadedKeys"
              :style="{height:height+'px'}"
              @select="handleSelect"
            >
              <template #title="{ id, name,type,data }">
                <a-dropdown :trigger="['contextmenu']">
                  <span>
                    <a-icon v-if="type === 'db'" type="database" class="mr-2" />
                    <a-icon v-if="type === 'table' || type === 'view_table'" type="table" class="mr-2" />
                    <a-icon v-if="type === 'proc' || type === 'view_proc' || type ==='data_set'" type="container" class="mr-2" />
                    <a-icon v-if="type === 'view'" type="eye" class="mr-2" />
                    {{ name }}
                  </span>
                  <template #overlay>
                    <a-menu v-if="type === 'db'" @click="({ key: menuKey }) => onContextMenuClickDB(id, menuKey,data)">
                      <a-menu-item key="1">创建新连接</a-menu-item>
                      <a-menu-item key="2">查看属性</a-menu-item>
                      <a-menu-item key="3">创建新表</a-menu-item>
                      <a-menu-item key="4">删除连接</a-menu-item>
                    </a-menu>
                    <a-menu v-else-if="type === 'table'" @click="({ key: menuKey }) => onContextMenuClickTable(id, menuKey,data)">
                      <a-menu-item key="1">删除当前表</a-menu-item>
                      <a-menu-item key="2">重命名</a-menu-item>
                      <a-menu-item key="3">清空当前表数据</a-menu-item>
                    </a-menu>
                  </template>
                </a-dropdown>
              </template>
            </a-tree>
        </a-card>
      </a-col>
      <a-col :md="18" >
        <a-card size="small" >
          <a-tabs default-active-key="1">
            <a-tab-pane key="column" tab=" 对象浏览器">
              <ColumnList :table="treeCurrentData" />
            </a-tab-pane>
            <a-tab-pane key="data" tab="数据浏览器" force-render>
              <TableDataList :table="treeCurrentData" />
            </a-tab-pane>
            <a-tab-pane key="sql" tab="SQL编辑器" force-render>
              <SQL :table="treeCurrentData" />
            </a-tab-pane>
          </a-tabs>
        </a-card>
      </a-col>
  </a-row>
  </a-spin>
  <DbConsoleModal ref="modalForm" @ok="loadDataDb" />
  <DbTableModal ref="DbTableModal" @ok="loadDataDb" />

</a-card>
</template>

<script>
import { Tree as ATree } from 'ant-design-vue'
import { getAction, deleteAction } from '@/services/manage'
import DbConsoleModal from './modules/DbConsoleModal'
import DbTableModal from './modules/DbTableModal'
import ColumnList from './modules/ColumnList'
import TableDataList from './modules/TableDataList'
import SQL from './modules/SQL'
export default {
  components: {
    ATree,
    DbConsoleModal,
    DbTableModal,
    ColumnList,
    TableDataList,
    SQL
  },
  data() {
    return {
      treeData: [],
      url: {
        db: '/dbconsole/db/list',
        table: '/dbconsole/table/list/',
        proc: '/dbconsole/proc/list/',
        delete: '/dbconsole/db/remove/',
        deleteDB: '/dbconsole/table/remove/',
        deleteData: '/dbconsole/data/remove/'
      },
      replaceFields: {
        children: 'children',
        title: 'name',
        key: 'id'
      },
      spinning: false,
      height: 0,
      loadedKeys: [],
      treeCurrentData: {}
    }
  },
  methods: {
    onContextMenuClickDB(treeKey, menuKey, data) {
      switch (menuKey) {
        case '1':
          this.handleAdd()
          break
        case '2':
          this.handleDetail(data)
          break
        case '3':
          this.handleAddTable(data)
          break
        case '4':
          this.handleDelete(treeKey)
          break
        default:
          break
      }
    },
    onContextMenuClickTable(treeKey, menuKey, data) {
      switch (menuKey) {
        case '1':
          this.handleDeleteTable(data)
          break
        case '2':
          this.handleEditTable(data)
          break
        case '3':
          this.handleDeleteData(data)
          break
        default:
          break
      }
    },
    loadDataDb() { // 查询连接信息
      this.spinning = true
      getAction(this.url.db).then(res => {
        if (res.success) {
          const data = []
          res.result.forEach(item => {
            data.push({
              id: item.id,
              name: item.name,
              data: item,
              type: 'db',
              children: [
                { id: 'table', name: '表', type: 'view_table', isLeaf: false, data: { dbData: item }},
                { id: 'proc', name: '存储过程', type: 'view_proc', isLeaf: false, data: { dbData: item }},
                { id: 'view', name: '视图', type: 'view', isLeaf: false, data: { dbData: item }},
                { id: 'data_set', name: '数据集', type: 'data_set', isLeaf: false, data: { dbData: item }}
              ]
            })
          })
          this.treeData = data
        }
      }).finally(() => {
        this.spinning = false
        this.loadedKeys = []
      })
    },
    loadDataTable(treeNode, dbInfoId) { // 查询表信息
      return getAction(this.url.table + dbInfoId).then(res => {
        if (res.success) {
          const data = []
          res.result.forEach(item => {
            item.dbData = { ...treeNode.dataRef.data.dbData }
            data.push({
              id: item.tableName,
              name: item.tableName,
              data: item,
              type: 'table',
              isLeaf: true
            })
          })
          this.loadedKeys.push(treeNode.dataRef.id)
          treeNode.dataRef.children = data
          this.treeData = [...this.treeData]
        }
      })
    },
    loadDataProc(treeNode, dbInfoId) { // 查询存储过程
      return getAction(this.url.proc + dbInfoId).then(res => {
        if (res.success) {
          const data = []
          res.result.forEach(item => {
            item.dbData = { ...treeNode.dataRef.data.dbData }
            data.push({
              id: item.procName,
              name: item.procName,
              data: item,
              type: 'proc',
              isLeaf: true
            })
          })
          this.loadedKeys.push(treeNode.dataRef.id)
          treeNode.dataRef.children = data
          this.treeData = [...this.treeData]
        }
      })
    },
    onLoadData(treeNode) {
      return new Promise(resolve => {
        if (treeNode.dataRef.children) {
          resolve()
          return
        }
        if (treeNode.dataRef.type === 'db') {
          resolve()
          return
        } else if (treeNode.dataRef.type === 'view_proc') {
          this.loadDataProc(treeNode, treeNode.$parent.dataRef.id).then(() => {
            resolve()
          })
        } else if (treeNode.dataRef.type === 'view') {
          console.log('--------')
        } else if (treeNode.dataRef.type === 'data_set') {
          console.log('--------')
        } else {
          this.loadDataTable(treeNode, treeNode.$parent.dataRef.id).then(() => {
            resolve()
          })
        }
      })
    },
    handleAdd() {
      this.$refs.modalForm.disableSubmit = false
      this.$refs.modalForm.add()
      this.$refs.modalForm.title = '创建新连接'
    },
    handleDetail(record) { // 查看详情
      this.$refs.modalForm.disableSubmit = true
      this.$refs.modalForm.edit(record)
      this.$refs.modalForm.title = '连接详情'
    },
    handleDelete(id) {
      deleteAction(this.url.delete + id).then(res => {
        if (res.success) {
          this.loadDataDb()
          this.$message.success('操作成功')
        }
      })
    },
    setTableHeight() { // 获取页面高度
      if (this.$refs.dbTree) {
        const clientHeight = document.documentElement.clientHeight
        const tableTop = this.$refs.dbTree.$el.getBoundingClientRect().top
        this.height = clientHeight - tableTop - 40
      }
    },
    handleAddTable(data) {
      this.$refs.DbTableModal.disableSubmit = false
      this.$refs.DbTableModal.add(data)
      this.$refs.DbTableModal.title = '创建新表'
    },
    handleEditTable(data) {
      this.$refs.DbTableModal.disableSubmit = false
      this.$refs.DbTableModal.edit(data)
      this.$refs.DbTableModal.title = '重命名'
    },
    handleDeleteTable(data) {
      deleteAction(this.url.deleteDB + data.dbInfoId + '/' + data.tableName).then(res => {
        if (res.success) {
          this.loadDataDb()
          this.$message.success('操作成功')
        }
      })
    },
    handleDeleteData(data) {
      deleteAction(this.url.deleteData + data.dbInfoId + '/' + data.tableName).then(res => {
        if (res.success) {
          this.loadDataDb()
          this.$message.success('操作成功')
        }
      })
    },
    handleSelect(selectedKeys, { selectedNodes, node }) {
      this.treeCurrentData = node.dataRef
    }
  },
  mounted() {
    this.loadDataDb()
    this.$nextTick(() => {
      this.setTableHeight()
    })
  }
}
</script>
<style lang="less">
  .db_console .ant-tabs-bar{
     margin-bottom: 8px;
  }
</style>
